<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>银行卡管理 - 银行业务管理系统</title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">

    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f8f9fa;
        }

        .navbar-brand {
            font-weight: bold;
            color: #007bff !important;
        }

        .sidebar {
            min-height: calc(100vh - 56px);
            background-color: #343a40;
            padding-top: 20px;
        }

        .sidebar .nav-link {
            color: #adb5bd;
            padding: 10px 20px;
            border-radius: 0;
        }

        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: #fff;
            background-color: #495057;
        }

        .main-content {
            padding: 20px;
        }

        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
            margin-bottom: 20px;
        }

        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid rgba(0, 0, 0, 0.125);
            font-weight: 600;
        }

        .table th {
            background-color: #f8f9fa;
            border-top: none;
            font-weight: 600;
        }

        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }

        .search-form {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .modal-header {
            background-color: #007bff;
            color: white;
        }

        .required {
            color: red;
        }

        .badge-report-loss {
            background-color: #dc3545;
        }

        .badge-normal {
            background-color: #28a745;
        }

        .money-amount {
            font-weight: bold;
            color: #28a745;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/admin">
                <i class="fas fa-university"></i>
                银行业务管理系统 - 管理员
            </a>

            <div class="navbar-nav ml-auto">
                <a class="nav-link" href="/">
                    <i class="fas fa-home"></i> 返回首页
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-2 d-none d-md-block sidebar">
                <div class="sidebar-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/admin">
                                <i class="fas fa-university"></i> 快捷操作
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/admin/customers">
                                <i class="fas fa-users"></i> 客户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/admin/cards">
                                <i class="fas fa-credit-card"></i> 银行卡管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/admin/deposit-types">
                                <i class="fas fa-piggy-bank"></i> 存款业务管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/admin/trades">
                                <i class="fas fa-exchange-alt"></i> 交易管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-toggle="collapse" data-target="#viewsSubmenu" aria-expanded="true">
                                <i class="fas fa-eye"></i> 视图查询 <i class="fas fa-caret-down"></i>
                            </a>
                            <div class="collapse show" id="viewsSubmenu">
                                <ul class="nav flex-column ml-3">
                                    <li class="nav-item">
                                        <a class="nav-link" href="/admin/views/customer-cards">
                                            <i class="fas fa-credit-card"></i> 客户银行卡视图
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="/admin/views/trade-details">
                                            <i class="fas fa-list-alt"></i> 交易明细视图
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-10 ml-sm-auto main-content">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-credit-card"></i> 银行卡管理
                    </h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group mr-2">
                            <button type="button" class="btn btn-primary" onclick="showAddModal()">
                                <i class="fas fa-plus"></i> 开设银行卡
                            </button>
                            <button type="button" class="btn btn-success" onclick="exportCards()">
                                <i class="fas fa-download"></i> 导出数据
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="refreshTable()">
                                <i class="fas fa-sync-alt"></i> 刷新
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 搜索表单 -->
                <div class="search-form">
                    <form id="searchForm">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchCardId">银行卡号</label>
                                    <input type="text" class="form-control" id="searchCardId" placeholder="精确查询">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchCustomerName">客户姓名</label>
                                    <input type="text" class="form-control" id="searchCustomerName" placeholder="支持模糊查询">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchSavingId">存款类型</label>
                                    <select class="form-control" id="searchSavingId">
                                        <option value="">全部类型</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchIsReportLoss">挂失状态</label>
                                    <select class="form-control" id="searchIsReportLoss">
                                        <option value="">全部状态</option>
                                        <option value="false">正常</option>
                                        <option value="true">已挂失</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchStartDate">开卡开始日期</label>
                                    <input type="date" class="form-control" id="searchStartDate">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchEndDate">开卡结束日期</label>
                                    <input type="date" class="form-control" id="searchEndDate">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="searchMinBalance">最小余额</label>
                                    <input type="number" class="form-control" id="searchMinBalance" step="0.01" min="0" placeholder="0.00">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>&nbsp;</label>
                                    <div>
                                        <button type="button" class="btn btn-primary" onclick="searchCards()">
                                            <i class="fas fa-search"></i> 查询
                                        </button>
                                        <button type="button" class="btn btn-secondary ml-2" onclick="resetSearch()">
                                            <i class="fas fa-undo"></i> 重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- 数据表格 -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-table"></i> 银行卡列表
                        <span class="badge badge-primary ml-2" id="totalCount">0</span>
                    </div>
                    <div class="card-body">
                        <div class="loading">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载数据...</p>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-striped table-hover" id="cardTable">
                                <thead>
                                    <tr>
                                        <th>银行卡号</th>
                                        <th>客户姓名</th>
                                        <th>存款类型</th>
                                        <th>开卡日期</th>
                                        <th>开卡金额</th>
                                        <th>账户余额</th>
                                        <th>挂失状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="cardTableBody">
                                    <!-- 数据将通过Ajax加载 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="分页导航">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 分页按钮将通过JavaScript生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 新增/编辑银行卡模态框 -->
    <div class="modal fade" id="cardModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="cardModalTitle">开设银行卡</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="cardForm" novalidate>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="cardId">银行卡号 <span class="required">*</span></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="cardId" name="cardId"
                                               required pattern="^[0-9]{16}$" placeholder="16位银行卡号" readonly>
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary" onclick="generateCardId()">
                                                <i class="fas fa-sync-alt"></i> 生成
                                            </button>
                                        </div>
                                    </div>
                                    <div class="invalid-feedback">请输入正确的16位银行卡号</div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customerId">客户 <span class="required">*</span></label>
                                    <select class="form-control" id="customerId" name="customerId" required>
                                        <option value="">请选择客户</option>
                                    </select>
                                    <div class="invalid-feedback">请选择客户</div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="savingId">存款类型 <span class="required">*</span></label>
                                    <select class="form-control" id="savingId" name="savingId" required>
                                        <option value="">请选择存款类型</option>
                                    </select>
                                    <div class="invalid-feedback">请选择存款类型</div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="openMoney">开卡金额 <span class="required">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">¥</span>
                                        </div>
                                        <input type="number" class="form-control" id="openMoney" name="openMoney"
                                               required min="1" step="0.01" placeholder="不少于1元">
                                    </div>
                                    <div class="invalid-feedback">开卡金额不能少于1元</div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="password">取款密码</label>
                                    <input type="password" class="form-control" id="password" name="password"
                                           pattern="^[0-9]{6}$" placeholder="6位数字密码，默认888888">
                                    <div class="invalid-feedback">密码必须为6位数字</div>
                                    <small class="form-text text-muted">留空则使用默认密码888888</small>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="curId">币种</label>
                                    <select class="form-control" id="curId" name="curId">
                                        <option value="RMB" selected>人民币(RMB)</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveCard()">
                        <i class="fas fa-save"></i> 开设银行卡
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;

        // 页面加载完成后初始化
        $(document).ready(function() {
            loadCards();
            loadDepositTypes();
            loadCustomers();
        });

        // 加载银行卡数据
        function loadCards(page = 1) {
            currentPage = page;
            showLoading(true);

            const searchParams = getSearchParams();
            const params = {
                current: currentPage,
                size: pageSize,
                ...searchParams
            };

            $.get('/admin/cards/page', params)
                .done(function(result) {
                    if (result.code === 200) {
                        renderTable(result.data);
                        renderPagination(result.data);
                        $('#totalCount').text(result.data.total);
                    } else {
                        showError('加载数据失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('网络请求失败，请检查网络连接');
                })
                .always(function() {
                    showLoading(false);
                });
        }

        // 加载存款类型
        function loadDepositTypes() {
            $.get('/admin/deposit-types/all')
                .done(function(result) {
                    if (result.code === 200) {
                        const searchSelect = $('#searchSavingId');
                        const formSelect = $('#savingId');

                        result.data.forEach(type => {
                            const option = `<option value="${type.savingId}">${type.savingName}</option>`;
                            searchSelect.append(option);
                            formSelect.append(option);
                        });
                    }
                });
        }

        // 加载客户列表
        function loadCustomers() {
            $.get('/admin/customers/page', { current: 1, size: 1000 })
                .done(function(result) {
                    if (result.code === 200) {
                        const select = $('#customerId');
                        result.data.records.forEach(customer => {
                            const option = `<option value="${customer.customerId}">${customer.customerName} (${customer.pid})</option>`;
                            select.append(option);
                        });
                    }
                });
        }

        // 获取搜索参数
        function getSearchParams() {
            return {
                cardId: $('#searchCardId').val().trim(),
                customerName: $('#searchCustomerName').val().trim(),
                savingId: $('#searchSavingId').val(),
                isReportLoss: $('#searchIsReportLoss').val(),
                startDate: $('#searchStartDate').val(),
                endDate: $('#searchEndDate').val(),
                minBalance: $('#searchMinBalance').val()
            };
        }

        // 渲染表格
        function renderTable(pageData) {
            const tbody = $('#cardTableBody');
            tbody.empty();

            if (pageData.records.length === 0) {
                tbody.append(`
                    <tr>
                        <td colspan="8" class="text-center text-muted">
                            <i class="fas fa-inbox fa-2x mb-2"></i><br>
                            暂无数据
                        </td>
                    </tr>
                `);
                return;
            }

            pageData.records.forEach(card => {
                const statusBadge = card.isReportLoss ?
                    '<span class="badge badge-report-loss">已挂失</span>' :
                    '<span class="badge badge-normal">正常</span>';

                const customerName = card.userInfo ? card.userInfo.customerName : '-';
                const depositTypeName = card.depositType ? card.depositType.savingName : '-';

                const row = `
                    <tr>
                        <td><code>${card.cardId}</code></td>
                        <td>${customerName}</td>
                        <td>${depositTypeName}</td>
                        <td>${formatDate(card.openDate)}</td>
                        <td class="money-amount">¥${formatMoney(card.openMoney)}</td>
                        <td class="money-amount">¥${formatMoney(card.balance)}</td>
                        <td>${statusBadge}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-info" onclick="viewCard('${card.cardId}')">
                                <i class="fas fa-eye"></i> 详情
                            </button>
                            <button class="btn btn-sm btn-outline-danger ml-1" onclick="deleteCard('${card.cardId}')">
                                <i class="fas fa-trash"></i> 销户
                            </button>
                            <button class="btn btn-sm btn-outline-warning ml-1" onclick="closeAccountWithdraw('${card.cardId}')">
                                <i class="fas fa-money-bill-wave"></i> 销户取款
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        }

        // 渲染分页
        function renderPagination(pageData) {
            const pagination = $('#pagination');
            pagination.empty();

            totalPages = pageData.pages;

            if (totalPages <= 1) return;

            // 上一页
            const prevDisabled = currentPage === 1 ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${prevDisabled}">
                    <a class="page-link" href="#" onclick="loadCards(${currentPage - 1})">上一页</a>
                </li>
            `);

            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                const active = i === currentPage ? 'active' : '';
                pagination.append(`
                    <li class="page-item ${active}">
                        <a class="page-link" href="#" onclick="loadCards(${i})">${i}</a>
                    </li>
                `);
            }

            // 下一页
            const nextDisabled = currentPage === totalPages ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${nextDisabled}">
                    <a class="page-link" href="#" onclick="loadCards(${currentPage + 1})">下一页</a>
                </li>
            `);
        }

        // 显示/隐藏加载动画
        function showLoading(show) {
            if (show) {
                $('.loading').show();
                $('#cardTable').hide();
            } else {
                $('.loading').hide();
                $('#cardTable').show();
            }
        }

        // 搜索银行卡
        function searchCards() {
            loadCards(1);
        }

        // 重置搜索
        function resetSearch() {
            $('#searchForm')[0].reset();
            loadCards(1);
        }

        // 刷新表格
        function refreshTable() {
            loadCards(currentPage);
        }

        // 显示新增模态框
        function showAddModal() {
            $('#cardModalTitle').text('开设银行卡');
            $('#cardForm')[0].reset();
            $('#curId').val('RMB');
            generateCardId();
            $('#cardModal').modal('show');
        }

        // 生成银行卡号
        function generateCardId() {
            $.get('/admin/cards/generate-card-id')
                .done(function(result) {
                    if (result.code === 200) {
                        $('#cardId').val(result.data);
                    } else {
                        showError('生成银行卡号失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('网络请求失败');
                });
        }

        // 保存银行卡
        function saveCard() {
            const form = $('#cardForm')[0];
            if (!form.checkValidity()) {
                form.classList.add('was-validated');
                showError('请检查表单填写是否正确');
                return;
            }

            // 验证必填字段
            const cardId = $('#cardId').val().trim();
            const customerId = $('#customerId').val();
            const savingId = $('#savingId').val();
            const openMoney = $('#openMoney').val();

            if (!cardId) {
                showError('银行卡号不能为空');
                return;
            }
            if (!customerId) {
                showError('请选择客户');
                return;
            }
            if (!savingId) {
                showError('请选择存款类型');
                return;
            }
            if (!openMoney || parseFloat(openMoney) < 1) {
                showError('开卡金额不能少于1元');
                return;
            }

            const cardData = {
                cardId: cardId,
                customerId: parseInt(customerId),
                savingId: parseInt(savingId),
                openMoney: parseFloat(openMoney),
                password: $('#password').val().trim() || null,
                curId: $('#curId').val()
            };

            console.log('提交的银行卡数据：', cardData);

            $.ajax({
                url: '/admin/cards',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(cardData)
            })
            .done(function(result) {
                console.log('开设银行卡响应：', result);
                if (result.code === 200) {
                    showSuccess('银行卡开设成功');
                    $('#cardModal').modal('hide');
                    loadCards(currentPage);
                } else {
                    showError('开设失败：' + result.message);
                }
            })
            .fail(function(xhr, status, error) {
                console.error('开设银行卡失败：', xhr, status, error);
                showError('网络请求失败：' + error);
            });
        }

        // 查看银行卡详情
        function viewCard(cardId) {
            $.get(`/admin/cards/${cardId}`)
                .done(function(result) {
                    if (result.code === 200) {
                        const card = result.data;
                        const customerName = card.userInfo ? card.userInfo.customerName : '未知';
                        const depositTypeName = card.depositType ? card.depositType.savingName : '未知';
                        const statusText = card.isReportLoss ? '已挂失' : '正常';

                        const detailHtml = `
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>银行卡号：</strong><code>${card.cardId}</code></p>
                                    <p><strong>客户姓名：</strong>${customerName}</p>
                                    <p><strong>存款类型：</strong>${depositTypeName}</p>
                                    <p><strong>币种：</strong>${card.curId}</p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>开卡日期：</strong>${formatDate(card.openDate)}</p>
                                    <p><strong>开卡金额：</strong><span class="money-amount">¥${formatMoney(card.openMoney)}</span></p>
                                    <p><strong>账户余额：</strong><span class="money-amount">¥${formatMoney(card.balance)}</span></p>
                                    <p><strong>挂失状态：</strong>${statusText}</p>
                                </div>
                            </div>
                        `;

                        showInfoModal('银行卡详情', detailHtml);
                    } else {
                        showError('获取银行卡信息失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('网络请求失败');
                });
        }

        // 删除银行卡（销户）
        function deleteCard(cardId) {
            // 先获取银行卡详情，检查余额
            $.get(`/admin/cards/${cardId}`)
                .done(function(result) {
                    if (result.code === 200) {
                        const card = result.data;
                        const balance = parseFloat(card.balance);

                        if (balance > 0) {
                            showError(`无法销户：银行卡余额为¥${balance.toFixed(2)}，请先将余额取出或转账至其他账户后再进行销户操作。\n\n建议：使用"销户取款"功能可以一次性取出所有余额并完成销户。`);
                            return;
                        }

                        // 余额为0，可以销户
                        if (confirm(`确定要销户银行卡"${cardId}"吗？\n\n销户后将无法恢复！\n当前余额：¥${balance.toFixed(2)}\n\n点击"确定"继续销户操作。`)) {
                            $.ajax({
                                url: `/admin/cards/${cardId}`,
                                method: 'DELETE'
                            })
                            .done(function(deleteResult) {
                                if (deleteResult.code === 200) {
                                    showSuccess('银行卡销户成功');
                                    loadCards(currentPage);
                                } else {
                                    showError('销户失败：' + deleteResult.message);
                                }
                            })
                            .fail(function() {
                                showError('销户请求失败，请稍后重试');
                            });
                        }
                    } else {
                        showError('获取银行卡信息失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('获取银行卡信息失败，请稍后重试');
                });
        }

        // 销户取款（一次性取出所有余额并销户）
        function closeAccountWithdraw(cardId) {
            // 先获取银行卡详情
            $.get(`/admin/cards/${cardId}`)
                .done(function(result) {
                    if (result.code === 200) {
                        const card = result.data;
                        const balance = parseFloat(card.balance);

                        if (balance <= 0) {
                            showError('银行卡余额为0，请直接使用普通销户功能。');
                            return;
                        }

                        // 显示确认对话框
                        const password = prompt(`销户取款确认\n\n银行卡号：${cardId}\n当前余额：¥${balance.toFixed(2)}\n\n此操作将：\n1. 取出所有余额（¥${balance.toFixed(2)}）\n2. 立即销户该银行卡\n3. 销户后无法恢复\n\n请输入取款密码确认操作：`);

                        if (password === null) {
                            return; // 用户取消
                        }

                        if (!password || password.length !== 6 || !/^\d{6}$/.test(password)) {
                            showError('请输入6位数字密码');
                            return;
                        }

                        // 询问备注
                        const remark = prompt('请输入备注信息（可选）：', '销户取款');

                        // 执行销户取款
                        $.ajax({
                            url: `/admin/cards/${cardId}/close-account-withdraw`,
                            method: 'POST',
                            data: {
                                password: password,
                                remark: remark || ''
                            }
                        })
                        .done(function(withdrawResult) {
                            if (withdrawResult.code === 200) {
                                showSuccess(`销户取款成功！\n取出金额：¥${withdrawResult.data.toFixed(2)}\n银行卡已销户`);
                                loadCards(currentPage);
                            } else {
                                showError('销户取款失败：' + withdrawResult.message);
                            }
                        })
                        .fail(function() {
                            showError('销户取款请求失败，请稍后重试');
                        });
                    } else {
                        showError('获取银行卡信息失败：' + result.message);
                    }
                })
                .fail(function() {
                    showError('获取银行卡信息失败，请稍后重试');
                });
        }

        // 导出银行卡数据
        function exportCards() {
            window.open('/admin/cards/export', '_blank');
        }

        // 显示信息模态框
        function showInfoModal(title, content) {
            const modalHtml = `
                <div class="modal fade" id="infoModal" tabindex="-1" role="dialog">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">${title}</h5>
                                <button type="button" class="close" data-dismiss="modal">
                                    <span>&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                ${content}
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // 移除已存在的模态框
            $('#infoModal').remove();
            $('body').append(modalHtml);
            $('#infoModal').modal('show');
        }

        // 工具函数
        function formatDate(date) {
            if (!date) return '-';
            return new Date(date).toLocaleDateString('zh-CN');
        }

        function formatMoney(amount) {
            if (amount == null || amount === '') return '0.00';
            return parseFloat(amount).toFixed(2);
        }

        function showSuccess(message) {
            showAlert('success', message);
        }

        function showError(message) {
            showAlert('danger', message);
        }

        function showAlert(type, message) {
            const alertHtml = `
                <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
                    ${message}
                    <button type="button" class="close" data-dismiss="alert">
                        <span>&times;</span>
                    </button>
                </div>
            `;

            $('.main-content').prepend(alertHtml);

            setTimeout(function() {
                $('.alert').alert('close');
            }, 3000);
        }
    </script>
</body>
</html>